本篇也是蓋地基的工作,先把error handling先規劃好。
NUXT官網有列出Nuxt3在跑時,可能會報出的幾種錯誤:
Nuxt is a full-stack framework, which means there are several sources of unpreventable user runtime errors that can happen in different contexts:
- Errors during the Vue rendering lifecycle (SSR & CSR)
 - Server and client startup errors (SSR + CSR)
 - Errors during Nitro server lifecycle (server/ directory)
 - Errors downloading JS chunks
 
想用最簡單暴力的方式來處理:報錯 -> 錯誤頁面
錯誤由throw createError({...})發起,進而導向根目錄的error.vue頁面。
至於handle的方式官網寫的滿清楚的。自己消化完後,我覺得需要處理的錯誤有兩種:
Call API時的錯誤:在[Day 10] 製作API Handling feat. Composable提到的try&catch裡處理。
系統性的錯誤(上面官網講的那些),官網也有說明怎麼處理;就是在plugin寫一個hook來捕捉:
// plugins/error-handler.ts
export default defineNuxtPlugin(nuxtApp => {
    const router = useRouter();
    nuxtApp.hook('vue:error', (error, instance, info) => {
        // 因為沒有log system,暫時還是先將錯誤用log印出來,以便找查錯誤
        console.error('error:', error);
        console.error('instance:', instance);
        console.error('info:', info);
        // 這邊是錯誤頁面給user看的訊息,系統內的問題多說無益,所以統一錯誤訊息
        throw showError({ statusMessage: 'Sorry, some internal issues occured, please give us some time to fix it' })
    });
});
// ./error.vue
<script setup>
    const error = useError();
    const handleError = () => {
        clearError({
            redirect: '/',
        });
    };
    definePageMeta({
        layout: false
    })
</script>
<template>
    <div>
        <h1>Error Page:{{ error.statusCode }}</h1>
        <div>{{ error.statusMessage }} 😮</div>
        <NuxtLink to="/" >Back to the INDEX</NuxtLink>
    </div>
</template>
<style>
    
</style>
// ./stores/useStore.ts
import { defineStore } from 'pinia';
import useAPI from '~/composables/useApi';
const storeName = 'test';
export const useTest = defineStore(storeName, () => {
    ...
    const testCallApi = async () =>  {
        return callAPI(`https://dummyjson.com/productssdfghjksdfghj`);
    }
    return {
        testCallApi,
        ...
    }
});
pages/index.vue創造一個錯誤
<script setup lang="ts">
...
onMounted(async () => {
  getGoog() // <--- 根本不存在
})
</script>